package BookFrame;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class Dao {
    private String filePath = "books.info"; // 图书数据文件
    private static Dao instance = null;
    private static List<Book> list; // 图书列表

    /**
     * 获取单例实例
     */
    public static Dao getInstance() {
        if (instance == null) {
            instance = new Dao();
        }
        return instance;
    }

    /** 构造方法 */
    public Dao() {
        list = readDataFromFile();
    }

    /** 从文件中读取图书数据 */
    private List<Book> readDataFromFile() {
        BufferedReader br;
        ArrayList<Book> list = new ArrayList<>();
        try {
            br = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(";");
                Book book = new Book();
                book.setBookId(Integer.parseInt(fields[0]));
                book.setTitle(fields[1]);
                book.setAuthor(fields[2]);
                book.setPublisher(fields[3]);
                book.setPublishDate(fields[4]);
                book.setCategory(fields[5]);
                book.setStock(Integer.parseInt(fields[6]));
                book.setStatus(fields[7]);
                book.setLocation(fields[8]);
                book.setBorrowerId(fields[9].isEmpty() ? 0 : Integer.parseInt(fields[9]));
                book.setBorrowDate(fields[10]);
                book.setDueDate(fields[11]);
                list.add(book);
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.out.println("图书数据文件不存在，将创建新文件");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /** 写数据到文件中 */
    private void writeDataIntoFile(List<Book> list) {
        BufferedWriter bw;
        try {
            bw = new BufferedWriter(new FileWriter(filePath));
            for (Book book : list) {
                String line = book.getBookId() + ";" +
                        book.getTitle() + ";" +
                        book.getAuthor() + ";" +
                        book.getPublisher() + ";" +
                        book.getPublishDate() + ";" +
                        book.getCategory() + ";" +
                        book.getStock() + ";" +
                        book.getStatus() + ";" +
                        book.getLocation() + ";" +
                        book.getBorrowerId() + ";" +
                        book.getBorrowDate() + ";" +
                        book.getDueDate();
                bw.write(line);
                bw.newLine();
            }
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 获取图书列表 */
    public List<Book> getList() {
        return list;
    }

    /** 获取表格数据 */
    public Vector<Vector> getBookDataByVector() {
        Vector<Vector> data = new Vector<>();
        for (Book book : list) {
            Vector row = new Vector();
            row.add(book.getBookId());
            row.add(book.getTitle());
            row.add(book.getAuthor());
            row.add(book.getCategory());
            row.add(book.getStatus());
            row.add(book.getStock());
            data.add(row);
        }
        return data;
    }

    /** 显示的列名 */
    public Vector<String> getBookColumnNames() {
        Vector<String> columnNames = new Vector<>();
        columnNames.add("图书编号");
        columnNames.add("书名");
        columnNames.add("作者");
        columnNames.add("类别");
        columnNames.add("状态");
        columnNames.add("库存");
        return columnNames;
    }

    /**
     * 通过图书编号和书名查询数据
     */
    public Vector<Vector> queryBooksByBookIdAndTitle(String bookId, String title) {
        Vector<Vector> data = getBookDataByVector();
        if (bookId == null && title == null)
            return data;

        Vector<Vector> queryData = new Vector<>();
        if (bookId == null && title != null) {
            for (Vector<String> row : data) {
                if (row.get(1).contains(title))
                    queryData.add(row);
            }
        } else if (bookId != null && title == null) {
            for (Vector row : data) {
                if ((Integer) row.get(0) == Integer.parseInt(bookId))
                    queryData.add(row);
            }
        } else {
            for (Vector row : data) {
                if ((Integer) row.get(0) == Integer.parseInt(bookId) && ((String) row.get(1)).contains(title))
                    queryData.add(row);
            }
        }
        return queryData;
    }

    /**
     * 通过图书编号查询数据
     */
    public Book queryBookByBookId(int bookId) {
        for (Book book : list) {
            if (bookId == book.getBookId())
                return book;
        }
        return null;
    }

    /**
     * 添加图书信息
     */
    public void addBook(Book book) {
        list.add(book);
        writeDataIntoFile(list);
    }

    /**
     * 删除图书
     */
    public void removeBookByBookId(int bookId) {
        Iterator<Book> it = list.iterator();
        while (it.hasNext()) {
            Book book = it.next();
            if (bookId == book.getBookId()) {
                it.remove();
                break;
            }
        }
        writeDataIntoFile(list);
    }

    /**
     * 更新图书数据
     */
    public void updateBookInfo(Book book) {
        for (int i = 0; i < list.size(); i++) {
            Book old = list.get(i);
            if (book.getBookId() == old.getBookId()) {
                list.set(i, book);
                break;
            }
        }
        writeDataIntoFile(list);
    }

    /**
     * 检验图书编号是否存在
     */
    public boolean bookIdHasExist(int bookId) {
        return queryBookByBookId(bookId) != null;
    }
}
